package com.yupi.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.mapper.QuestionSubmitMapper;
import com.yupi.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.oj.model.entity.QuestionInfo;
import com.yupi.oj.model.entity.QuestionSubmit;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.enums.JudgeStatusEnum;
import com.yupi.oj.model.enums.LanguageTypeEnum;
import com.yupi.oj.service.QuestionInfoService;
import com.yupi.oj.service.QuestionSubmitService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 1
* @description 针对表【question_submit(提交记录)】的数据库操作Service实现
* @createDate 2023-09-04 21:51:03
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{
    @Resource
    private QuestionInfoService questionInfoService;

    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return 提交记录的id
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {

        String language = questionSubmitAddRequest.getLanguage();
        Long questionId = questionSubmitAddRequest.getQuestionId();
        String code = questionSubmitAddRequest.getCode();

        QuestionInfo questionInfo = questionInfoService.getById(questionId);
        if (questionInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //获取提交用户的id
        Long userId = loginUser.getId();

        //根据题目id和用户id查询表，获取到该用户做该道题的所有记录，如果有正在判题或者等待判题的记录时，则返回等待
        LambdaQueryWrapper<QuestionSubmit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuestionSubmit::getQuestionId,questionId).eq(QuestionSubmit::getUserId,userId);
        List<QuestionSubmit> submits = list(queryWrapper);
        for (QuestionSubmit submit : submits) {
            if(JudgeStatusEnum.WAITING.getStatusId() == submit.getStatus() || JudgeStatusEnum.JUDGING.getStatusId() == submit.getStatus() ){
                throw new BusinessException(ErrorCode.REPEAT_SUBMIT_ERROR);
            }
        }

        //封装提交信息的参数，设置判题状态为待判题状态中，判题信息初始化为空
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(code);
        questionSubmit.setLanguage(language);
        questionSubmit.setStatus(JudgeStatusEnum.WAITING.getStatusId());
        questionSubmit.setJudgeInfo("{}");
        boolean res = this.save(questionSubmit);
        if(!res){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }
        return questionSubmit.getId();
        
    }

//    /**
//     * 封装了事务的方法
//     *
//     * @param userId
//     * @param questionId
//     * @return
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public int doQuestionSubmitInner(long userId, long questionId) {
//        QuestionSubmit questionSubmit = new QuestionSubmit();
//        questionSubmit.setUserId(userId);
//        questionSubmit.setQuestionId(questionId);
//        QueryWrapper<QuestionSubmit> thumbQueryWrapper = new QueryWrapper<>(questionSubmit);
//        QuestionSubmit oldQuestionSubmit = this.getOne(thumbQueryWrapper);
//        boolean result;
//        // 已题目提交
//        if (oldQuestionSubmit != null) {
//            result = this.remove(thumbQueryWrapper);
//            if (result) {
//                // 题目提交数 - 1
//                result = questionInfoService.update()
//                        .eq("id", questionId)
//                        .gt("thumbNum", 0)
//                        .setSql("thumbNum = thumbNum - 1")
//                        .update();
//                return result ? -1 : 0;
//            } else {
//                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
//            }
//        } else {
//            // 未题目提交
//            result = this.save(questionSubmit);
//            if (result) {
//                // 题目提交数 + 1
//                result = questionInfoService.update()
//                        .eq("id", questionId)
//                        .setSql("thumbNum = thumbNum + 1")
//                        .update();
//                return result ? 1 : 0;
//            } else {
//                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
//            }
//        }
//    }
}




